from flask import Blueprint, request, jsonify
from app import db

userR = Blueprint('users', __name__)

class UserModel(db.Model):
    __tablename__='t_users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    pwd = db.Column(db.String(50), nullable=False)

# 创建用户
@userR.route('/users', methods=['POST'])
def create_user():
    data = request.get_json()
    name = data.get('name')
    pwd = data.get('pwd')

    if not name or not pwd:
        return jsonify({'error': 'Name and pwd are required.'}), 400

    user = UserModel(name=name, pwd=pwd)
    db.session.add(user)
    db.session.commit()

    return jsonify({'message': 'User created successfully.'}), 201


# 获取所有用户
@userR.route('/users', methods=['GET'])
def get_users():
    users = UserModel.query.all()
    output = []
    for user in users:
        user_data = {
            'id': user.id,
            'name': user.name,
            'pwd': user.pwd
        }
        output.append(user_data)
    return jsonify(output)


# 获取单个用户
@userR.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    user = UserModel.query.get_or_404(user_id)
    return jsonify({
        'id': user.id,
        'name': user.name,
        'pwd': user.pwd
    })


# 更新用户
@userR.route('/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    user = UserModel.query.get_or_404(user_id)
    data = request.get_json()

    if 'name' in data:
        user.name = data['name']
    if 'pwd' in data:
        user.pwd = data['pwd']

    db.session.commit()

    return jsonify({'message': 'User updated successfully.'})


# 删除用户
@userR.route('/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    user = UserModel.query.get_or_404(user_id)
    db.session.delete(user)
    db.session.commit()

    return jsonify({'message': 'User deleted successfully.'})
